package com.fy56.platform.goodsTracking.commons.security;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

public class Utility {
    public Utility() {
    }

    //根据分隔符strDelimter将strContent解析，得到分解后的enum
    @SuppressWarnings("rawtypes")
    public static Enumeration splitSeparater(String str, String separater) {
        String tempStr = str.trim();
        Vector<String> container = new Vector<String>();
        StringTokenizer st = new StringTokenizer(tempStr, separater);
        String temp = "";

        while (st.hasMoreElements()) {
            temp = st.nextToken();
            temp = temp.trim();

            if (!temp.equalsIgnoreCase("")) {
                container.add(temp);
            }
        }

        return container.elements();
    }

    //根据分隔符strDelimter将strContent解析，得到分解后的字符串数组
    public static String[] split(String strContent, String strDelimiter) {
        
        if ((strContent == null) || (strDelimiter == null)) {//如果没有内容或者分割符，则直接返回空！
            return null;
        }

        StringTokenizer st = new StringTokenizer(strContent, strDelimiter);
        
        int nCount = st.countTokens();//如果没有分割符，则直接返回空！
        
        String[] contents = new String[nCount];//解析内容

        for (int i = 0; (i < nCount) && st.hasMoreTokens(); i++) {
            contents[i] = st.nextToken().trim();
        }

        return contents;
    }

    public static String[] parseCommand(String strCommand) {
        return split(strCommand, " ");
    }
    
    public static int getInt(String hexStr) {//16进制字符串 <=> int
        int[] digit = new int[4];
        int result = 0;

        for (int i = 0; i < 4; i++) {
            digit[i] = Integer.parseInt(hexStr.substring(i * 2, (i * 2) + 2), 16);
        }

        result = digit[0] + (digit[1] * 256) + (digit[2] * 256 * 256) +
            (digit[3] * 256 * 256 * 256);

        return result;
    }
    
    public static int getShort(String hexStr) {//	16进制字符串 <=> short
        int[] digit = new int[2];
        int result;

        for (int i = 0; i < 2; i++) {
            digit[i] = Integer.parseInt(hexStr.substring(i * 2, (i * 2) + 2), 16);
        }

        result = (digit[0] + (digit[1] * 256));

        return result;
    }
    
    public static String toHexString(String str) {//	16进制字符串 <=> 字符串  如“0x31323334” => "1234"
        // byte temp[] = new byte[str.length()];
        byte[] temp = str.getBytes();
        String result = "";

        for (int i = 0; i < temp.length; i++) {
            result += toHexString(temp[i]);
        }

        return result;
    }
    
    public static String toHexString(byte[] b) {//	字节数组 <=> 16进制字符串
        String result = "";

        try {
            for (int i = 0; i < b.length; i++) {
                result += toHexString(b[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    
    public static String toHexString(byte[] b, int offset, int len) {//	字节数组 <=> 16进制字符串
        String result = "";

        try {
            for (int i = offset; i < (len + offset); i++) {
                result += toHexString(b[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    
    public static String toHexString(int op) {//	int <=> 16进制字符串
        int[] temp = new int[4];
        String s = "";

        for (int i = 0; i < 4; i++) {
            temp[i] = (op & (0x000000ff << (i * 8))) >> (i * 8);
            s += toHexString((byte) temp[i]);
        }

        return s;
    }
    
    public static String toHexString(short op) {//	short <=> 16进制字符串
        int[] temp = new int[2];
        String s = "";

        for (int i = 0; i < 2; i++) {
            temp[i] = (op & (0x000000ff << (i * 8))) >> (i * 8);
            s += toHexString((byte) temp[i]);
        }

        return s;
    }
    
    public static String toHexString(byte b) {//	byte <=> 16进制字符串
        int tmp = (b & 0x000000f0) >> 4;
        String result = Integer.toHexString(tmp);
        tmp = b & 0x0000000f;
        result += Integer.toHexString(tmp);

        return result;
    }
    
    public static byte[] arrayCopy(byte[] src, int offset, int len)//return arrycopy
        throws ArrayIndexOutOfBoundsException {
        byte[] destination = null;

        if ((len <= 0) || (len > (src.length - offset + 1)) || (src == null) || (src.length <= 0)) {

            throw new ArrayIndexOutOfBoundsException("the array is out of length!" + "src.length=" + src.length + " :len=" + len);
        }
       
        destination = new byte[len]; //dest=new byte[len];

        for (int ii = 0; ii < len; ii++) {            
            destination[ii] = src[offset + ii];//dest[ii]=src[offset+ii];
        }

        return destination;
    }
    
    public static String HexStrToStr(String hexStr, int msg_fmt) {//16进制--->>字符串
        String result = "";
        int len = hexStr.length();
        int i = 0;
        int temp1;
        int temp2;

        if (msg_fmt == 8) {
            i = len / 4;

            char[] temp = new char[i];

            for (int j = 0; j < i; j++) {
                temp1 = Integer.parseInt(hexStr.substring(j * 4, (j * 4) + 2),16);
                temp2 = Integer.parseInt(hexStr.substring((j * 4) + 2,(j * 4) + 4), 16);
                temp1 = (temp1 & 0xff) << 8;
                temp2 = temp2 & 0xff;
                temp[j] = (char) (temp1 | temp2);
            }

            try {
                result = new String(temp);
            } catch (Exception e) {
                e.printStackTrace();

                return result;
            }
        } else if ((msg_fmt == 15) || (msg_fmt == 0)) {
            i = len / 2;

            byte[] bytes = new byte[i];

            for (int j = 0; j < i; j++) {
                temp1 = Integer.parseInt(hexStr.substring(j * 2, (j * 2) + 2),16);
                bytes[j] = (byte) temp1;
            }

            try {
                Charset charset = Charset.forName("gbk");
                ByteBuffer buffer = ByteBuffer.wrap(bytes);
                CharBuffer charbuffer = charset.decode(buffer);
                result = charbuffer.toString();

                // sun.io.ByteToCharConverter;
                //ByteToCharConverter toChar = ByteToCharConverter.getConverter("gb2312");
                //result = new String(toChar.convertAll(bytes));
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }
        }

        return result;
    }
    
    public static String retoHexString(int op) {//	int <=> 16进制字符串
        int[] temp = new int[4];
        String s = "";

        for (int i = 3; i >= 0; i--) {
            temp[i] = (op & (0x000000ff << (i * 8))) >> (i * 8);
            s += toHexString((byte) temp[i]);
        }

        return s;
    }

    //	short <=> 16进制字符串
    public static String retoHexString1(short op) {
        int[] temp = new int[2];
        String s = "";

        for (int i = 1; i >= 0; i--) {
            temp[i] = (op & (0x000000ff << (i * 8))) >> (i * 8);
            s += toHexString((byte) temp[i]);
        }

        return s;
    }
    
    public static byte[] connectTwoBytes(byte[] cache, byte[] b) {//连接两个byte数组
        byte[] res = new byte[cache.length + b.length];
        System.arraycopy(cache, 0, res, 0, cache.length);
        System.arraycopy(b, 0, res, cache.length, b.length);

        return res;
    }

    public static String generate86MDN(String mdn) {
        String result = mdn;

        if ((mdn != null) && !"".equals(mdn)) {
            if (mdn.length() >= 11) {
                result = "86" + mdn.substring(mdn.length() - 11);
            }
        }

        return result;
    }

    public static String toStringHex(String s) {
        byte[] baKeyword = new byte[s.length() / 2];

        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, (i * 2) + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            s = new String(baKeyword, "utf-8"); //UTF-16le:Not 
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return s;
    }

    /**
     * 将一个整数转成二进制数组
     * @param value
     * @return String
     */
    public static byte[] intToBinaryArr(int value) {
        
        String bits = Integer.toBinaryString(value);//转成二进制
        StringBuffer temp = new StringBuffer();

        
        if (bits.length() < 8) {//不足8位前补0
            int s = 8 - bits.length();

            for (int i = 0; i < s; i++) {
                temp.append("0");
            }

            bits = temp + bits;
            temp = null;
        }

        return bits.getBytes();
    }

    /**
     * 整数转成长度为2的字节数组,整数不能Short的取取值范围
     * @param n
     * @return
     */
    public static byte[] int2TwoByteArray(int n) throws Exception {

        byte[] b = new byte[2];

        b[0] = (byte) ((n >> 8) & 0xFF);
        b[1] = (byte) (n & 0xFF);

        return b;
    }
    
    public static String intToHex(int i) {// 十进制转成十六进制：
        return Integer.toHexString(i);
    }
    
    public static String intToOct(int i) {// 十进制转成八进制
        return Integer.toOctalString(i);
    }
    
    public static String intToBinary(int i) {// 十进制转成二进制
        return Integer.toBinaryString(i);
    }
    
    public static int hexToInt(String i) {// 十六进制转成十进制
        return Integer.valueOf(i, 16);
    }
    
    public static int octToInt(String i) {// 八进制转成十进制
        return Integer.valueOf(i, 8);
    }
    
    public static int binaryToInt(String i) {// 二进制转十进制
        return Integer.valueOf(i, 2);
    }

    /**
    * 整型转换为4位字节数组
    * @param intValue
    * @return
    */
    public static byte[] int2Byte(int intValue) {
        byte[] b = new byte[4];

        for (int i = 0; i < 4; i++) {
            b[i] = (byte) ((intValue >> (8 * (3 - i))) & 0xFF);
        }

        return b;
    }

    /**
     * 4位字节数组转换为整型
     * @param b
     * @return
     */
    public static int byte2Int(byte[] b) {
        int intValue = 0;

        //        int tempValue = 0xFF;   
        for (int i = 0; i < b.length; i++) {
            intValue += ((b[i] & 0xFF) << (8 * (3 - i)));  
        }

        return intValue;
    }

    /**
     * 字节数组转换成整数，不能超过两个字节
     * @param b
     * @return
     */
    public static int twoBytesArray2int(byte[] b) throws Exception {
        if ((b == null) || (b.length == 0) || (b.length > 2)) {
            throw new Exception("字节数据为空或长度超过两位");
        }

        int mask = 0xff;

        int temp = 0;
        int res = 0;

        for (int i = 0; i < 2; i++) {
            res <<= 8;
            temp = b[i] & mask;
            res |= temp;
        }

        return res;
    }

    /**
      * 把16进制字符串转换成字节数组
      * @param hex
      * @return
      */
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();

        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) ((toByte(achar[pos]) << 4) |
                toByte(achar[pos + 1]));
        }

        return result;
    }
    
    public static byte[] toBytesByHexString(String in) {//字节数组 <=> 16进制字符串
        byte[] result = null;

        try {
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);

        return b;
    }

    public static void main(String[] args) {

        try {
            byte[] e = new byte[6];
            System.arraycopy(Utility.int2TwoByteArray(1 + 1), 0, e, 4, 2);

            byte[] b = new byte[2];
            System.arraycopy(e, 4, b, 0, 2);

            int d = Utility.twoBytesArray2int(b);
            System.out.println(Utility.toHexString(Utility.int2Byte(223095690)));
            System.out.println(Utility.toHexString(Utility.intToBinaryArr(223095690)));
            
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
